package com.xjscrm.console.service.customer.materialLibrary.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.xjscrm.common.constant.ResponseMsg;
import com.xjscrm.common.entity.*;
import com.xjscrm.common.exception.BusinessException;
import com.xjscrm.common.result.ResponseCode;
import com.xjscrm.common.utils.DateUtil;
import com.xjscrm.common.utils.OrderByUtil;
import com.xjscrm.common.vo.msg.MsgData;
import com.xjscrm.console.mapper.*;
import com.xjscrm.console.param.BaseDto;
import com.xjscrm.console.param.materialLibrary.*;
import com.xjscrm.console.service.customer.materialLibrary.MaterialLibraryService;
import com.xjscrm.console.service.customer.materialLibrary.MaterialLibrarybBtchService;
import com.xjscrm.console.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class MaterialLibraryServiceImpl implements MaterialLibraryService {


    @Autowired
    private MaterialTagMapper materialTagMapper;

    @Autowired
    private MaterialTagRelationMapper materialTagRelationMapper;

    @Autowired
    private MaterialMapper materialMapper;

    @Autowired
    private MaterialConfigMapper materialConfigMapper;

    @Autowired
    private MaterialConfigGroupMapper materialConfigGroupMapper;

    @Autowired
    private WwDeviceMapper wwDeviceMapper;

    @Autowired
    private MaterialLibrarybBtchService materialLibrarybBtchService;

    @Autowired
    private WwGroupMapper wwGroupMapper;

    @Override
    public Long addMaterialLibraryTag(MaterialLibraryTagDto materialLibraryTagDto) {

        if (materialLibraryTagDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (materialLibraryTagDto.getType() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "素材类型不能为空");
        }
        if (StringUtils.isBlank(materialLibraryTagDto.getName())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "名称不能为空");
        }
        if (StringUtils.isBlank(materialLibraryTagDto.getUpdateUser())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "更新人不能为空");
        }
        if (materialLibraryTagDto.getOperatorType() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "账号类型错误");
        }
        //如果子账号上传的是个人素材类型标签，必须有子账号ID
        if (materialLibraryTagDto.getOperatorType() == 1 && materialLibraryTagDto.getChildId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "子账号ID不存在");
        }

        //主账号操作时保存的是主账号id
        if (materialLibraryTagDto.getOperatorType() == 0) {
            materialLibraryTagDto.setChildId(materialLibraryTagDto.getMerId());
        }

        int time = DateUtil.getTime();

        MaterialTag materialTag = new MaterialTag();
        BeanUtil.copyProperties(materialLibraryTagDto, materialTag);
        materialTag.setId(IdWorker.getId());
        materialTag.setCreateTime(time);
        materialTag.setUpdateTime(time);
        materialTagMapper.insert(materialTag);

        return materialTag.getId();
    }


    @Override
    public void updateMaterialLibraryTag(MaterialLibraryTagDto materialLibraryTagDto) {

        if (materialLibraryTagDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (materialLibraryTagDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        if (StringUtils.isBlank(materialLibraryTagDto.getUpdateUser())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "更新人不能为空");
        }
        if (StringUtils.isBlank(materialLibraryTagDto.getName())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "标签名称不能为空");
        }
        if (materialLibraryTagDto.getOperatorType() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "账号类型错误");
        }
        //如果子账号上传的是个人素材类型标签，必须有子账号ID
        if (materialLibraryTagDto.getOperatorType() == 1 && materialLibraryTagDto.getChildId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "子账号ID不存在");
        }

        //主账号操作时保存的是主账号id
        if (materialLibraryTagDto.getOperatorType() == 0) {
            materialLibraryTagDto.setChildId(materialLibraryTagDto.getMerId());
        }


        MaterialTag materialTag = materialTagMapper.getById(materialLibraryTagDto.getId(), materialLibraryTagDto.getMerId());

        if (materialTag == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该标签不存在");
        }

        materialTag.setName(materialLibraryTagDto.getName());
        materialTag.setUpdateUser(materialLibraryTagDto.getUpdateUser());
        materialTag.setName(materialLibraryTagDto.getName());

        materialTagMapper.update(materialTag);
    }

    @Override
    public Object getMaterialLibraryTagList(MaterialLibraryTagQuery materialLibraryTagQuery) {

        if (materialLibraryTagQuery.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (materialLibraryTagQuery.getOperatorType() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "账号类型为空");
        }
        //如果查询人是子账号，必须有子账号ID
        if (materialLibraryTagQuery.getOperatorType() == 1 && materialLibraryTagQuery.getChildId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "子账号ID不存在");
        }
        if (materialLibraryTagQuery.getType() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "类型不能为空");
        }
        if (materialLibraryTagQuery.getType() == 1) {
            materialLibraryTagQuery.setChildId(null);
        }
        //主账号查看个人素材，子账号为主账号ID
        if (materialLibraryTagQuery.getType() == 2) {
            if (materialLibraryTagQuery.getOperatorType() == 0 && materialLibraryTagQuery.getChildId() == null) {
                materialLibraryTagQuery.setChildId(materialLibraryTagQuery.getMerId());
            }
        }

        String orderBy = OrderByUtil.getOrderBy(materialLibraryTagQuery.getOrderByField(), materialLibraryTagQuery.isAsc());
        PageHelper.startPage(materialLibraryTagQuery.getCurrent(), materialLibraryTagQuery.getSize(), orderBy);

        List<MaterialLibraryTagVo> materialLibraryTagVoList = materialTagMapper.getMaterialLibraryTagList(materialLibraryTagQuery);

        return new MyPageInfo<>(materialLibraryTagVoList);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delMaterialLibraryTag(BatchdelMaterialLibraryDto batchdelMaterialLibraryDto) {

        if (batchdelMaterialLibraryDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (batchdelMaterialLibraryDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }

        MaterialTag materialTag = materialTagMapper.getById(batchdelMaterialLibraryDto.getId(), batchdelMaterialLibraryDto.getMerId());

        if (materialTag == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该标签不存在");
        }

        //先删除 标签和素材关系
        MaterialTagRelationQuery materialTagRelationQuery = new MaterialTagRelationQuery();
        materialTagRelationQuery.setMerId(materialTag.getMerId());
        materialTagRelationQuery.setTagId(materialTag.getId());
        List<MaterialTagRelationVo> materialTagRelationVoList = materialTagRelationMapper.getMaterialTagRelationList(materialTagRelationQuery);
        if (materialTagRelationVoList != null && !materialTagRelationVoList.isEmpty()) {
            materialTagRelationVoList.forEach(it -> materialTagRelationMapper.delById(it.getId(), it.getMerId()));
        }


        //再删除标签
        materialTagMapper.delById(materialTag.getId(), materialTag.getMerId());

    }


    @Override
    public Object getMaterialLibraryTagDropDown(MaterialLibraryTagDto materialLibraryTagDto) {

        if (materialLibraryTagDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (materialLibraryTagDto.getOperatorType() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "账号类型为空");
        }
        if (materialLibraryTagDto.getType() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "类型不能为空");
        }
        //如果查询人是子账号，必须有子账号ID
        if (materialLibraryTagDto.getOperatorType() == 1 && materialLibraryTagDto.getChildId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "子账号ID不存在");
        }


        MaterialLibraryTagQuery materialLibraryTagQuery = new MaterialLibraryTagQuery();
        materialLibraryTagQuery.setMerId(materialLibraryTagDto.getMerId());
        materialLibraryTagQuery.setType(materialLibraryTagDto.getType());

        if (materialLibraryTagDto.getType() == 1) {
            materialLibraryTagQuery.setChildId(null);
        }
        //主账号查看个人素材，子账号为主账号ID
        if (materialLibraryTagDto.getType() == 2) {
            if (materialLibraryTagDto.getOperatorType() == 0 && materialLibraryTagDto.getChildId() == null) {
                materialLibraryTagQuery.setChildId(materialLibraryTagDto.getMerId());
            }
            if (materialLibraryTagDto.getOperatorType() == 1) {
                materialLibraryTagQuery.setChildId(materialLibraryTagDto.getChildId());
            }
        }

        List<MaterialLibraryTagVo> materialLibraryTagVoList = materialTagMapper.getMaterialLibraryTagList(materialLibraryTagQuery);

        if (materialLibraryTagVoList == null || materialLibraryTagVoList.isEmpty()) {
            return null;
        }

        List<Map> mapArrayList = new ArrayList<>();
        for (MaterialLibraryTagVo materialLibraryTagVo : materialLibraryTagVoList) {
            try {
                HashMap<String, Object> map = new HashMap<>();
                map.put("label", materialLibraryTagVo.getName());
                map.put("value", materialLibraryTagVo.getId());
                mapArrayList.add(map);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return mapArrayList;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addMaterialLibrary(MaterialDto materialDto) {
        if (materialDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (materialDto.getType() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "类型不能为空");
        }
        if (StringUtils.isBlank(materialDto.getUpdateUser())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "更新人不能为空");
        }
        if (materialDto.getMsgType() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "素材类型不能为空");
        }
        if (materialDto.getOperatorType() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "账号类型错误");
        }
        //子账号必须要有子账号id
        if (materialDto.getOperatorType() == 1 && materialDto.getChildId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "子账号ID不存在");
        }
        //主账号操作时保存的是主账号id
        if (materialDto.getOperatorType() == 0) {
            materialDto.setChildId(materialDto.getMerId());
        }


        //获取素材库配置
        MaterialConfig materialConfig = materialConfigMapper.getByMerIdAndChildId(materialDto.getMerId(), materialDto.getChildId());


        //企业素材库限制2000条，个人素材库限制1000条
        List<MaterialVo> delMaterialVoList = new ArrayList<>();
        if (materialDto.getType() == 1) {
            //获取企业素材条数
            Integer num = materialMapper.getEnterpriseCountByMerId(materialDto.getMerId());
            if (num != null && num >= 2000) {
                if (materialConfig == null || materialConfig.getEnterpriseClean() == null || materialConfig.getEnterpriseClean() == 0) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "企业素材库已满，企业素材自动清理未开启");
                }
                //删除最后10条
                MaterialQuery materialQuery = new MaterialQuery();
                materialQuery.setMerId(materialDto.getMerId());
                materialQuery.setType(1);
                materialQuery.setCurrent(1);
                materialQuery.setSize(10);
                materialQuery.setAsc(true);
                materialQuery.setOrderByField("create_time");
                //企业重要素材不清理，只查询不重要素材
                if (materialConfig.getEnterpriseClean() == 1 && materialConfig.getEnterpriseImportantClean() != null && materialConfig.getEnterpriseImportantClean() == 1) {
                    materialQuery.setImportant(0);
                }
                String orderBy = OrderByUtil.getOrderBy(materialQuery.getOrderByField(), materialQuery.isAsc());
                PageHelper.startPage(materialQuery.getCurrent(), materialQuery.getSize(), orderBy);
                delMaterialVoList = materialMapper.getMaterialLibraryList(materialQuery);
            }
        }
        if (materialDto.getType() == 2) {
            //获取个人素材条数
            Integer num = materialMapper.getPersonalCountByMerIdAndChildId(materialDto.getMerId(), materialDto.getChildId());
            if (num != null && num >= 1000) {

                if (materialConfig == null || materialConfig.getPrivateClean() == null || materialConfig.getPrivateClean() == 0) {
                    throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "个人素材库已满，个人素材自动清理未开启");
                }
                //删除最后10条
                MaterialQuery materialQuery = new MaterialQuery();
                materialQuery.setMerId(materialDto.getMerId());
                materialQuery.setChildId(materialDto.getChildId());
                materialQuery.setType(2);
                materialQuery.setCurrent(1);
                materialQuery.setSize(10);
                materialQuery.setAsc(true);
                materialQuery.setOrderByField("create_time");
                //个人重要素材不清理，只查询不重要素材
                if (materialConfig.getPrivateClean() == 1 && materialConfig.getPrivateImportantClean() != null && materialConfig.getPrivateImportantClean() == 1) {
                    materialQuery.setImportant(0);
                }
                String orderBy = OrderByUtil.getOrderBy(materialQuery.getOrderByField(), materialQuery.isAsc());
                PageHelper.startPage(materialQuery.getCurrent(), materialQuery.getSize(), orderBy);
                delMaterialVoList = materialMapper.getMaterialLibraryList(materialQuery);
            }
        }

        //进行批量删除
        if (!delMaterialVoList.isEmpty()) {
            List<Long> ids = delMaterialVoList.stream().map(MaterialVo::getId).distinct().collect(Collectors.toList());
            BatchdelMaterialLibraryDto batchdelMaterialLibraryDto = new BatchdelMaterialLibraryDto();
            batchdelMaterialLibraryDto.setMerId(materialDto.getMerId());
            batchdelMaterialLibraryDto.setIds(ids);
            materialLibrarybBtchService.batchDelMaterialLibrary(batchdelMaterialLibraryDto);
        }


        Material material = new Material();
        BeanUtil.copyProperties(materialDto, material);

        if (materialDto.getMsgDataList() != null && !materialDto.getMsgDataList().isEmpty()) {
            material.setMsgDatas(JSONObject.toJSONString(materialDto.getMsgDataList()));
        }

        materialMapper.add(material);

        //添加素材和标签的关系
        if (materialDto.getTagIdList() != null && !materialDto.getTagIdList().isEmpty()) {
            for (Long tagId : materialDto.getTagIdList()) {
                MaterialTagRelation materialTagRelation = new MaterialTagRelation();
                materialTagRelation.setMerId(material.getMerId());
                materialTagRelation.setMaterialId(material.getId());
                materialTagRelation.setTagId(tagId);
                materialTagRelationMapper.add(materialTagRelation);
            }
        }

    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateMaterialLibrary(MaterialDto materialDto) {
        if (materialDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (materialDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        if (materialDto.getType() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "类型不能为空");
        }
        if (StringUtils.isBlank(materialDto.getUpdateUser())) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "更新人不能为空");
        }
        if (materialDto.getMsgType() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "素材类型不能为空");
        }
        if (materialDto.getOperatorType() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "账号类型错误");
        }
        //子账号必须要有子账号id
        if (materialDto.getOperatorType() == 1 && materialDto.getChildId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "子账号ID不存在");
        }
        //主账号操作时保存的是主账号id
        if (materialDto.getOperatorType() == 0) {
            materialDto.setChildId(materialDto.getMerId());
        }

        Material material = materialMapper.getById(materialDto.getId(), materialDto.getMerId());

        if (material == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该素材不存在");
        }

        BeanUtil.copyProperties(materialDto, material);

        if (materialDto.getMsgDataList() != null && !materialDto.getMsgDataList().isEmpty()) {
            material.setMsgDatas(JSONObject.toJSONString(materialDto.getMsgDataList()));
        }

        materialMapper.update(material);


        //先删除 标签和素材关系
        MaterialTagRelationQuery materialTagRelationQuery = new MaterialTagRelationQuery();
        materialTagRelationQuery.setMerId(material.getMerId());
        materialTagRelationQuery.setMaterialId(material.getId());
        List<MaterialTagRelationVo> materialTagRelationVoList = materialTagRelationMapper.getMaterialTagRelationList(materialTagRelationQuery);
        if (materialTagRelationVoList != null && !materialTagRelationVoList.isEmpty()) {
            materialTagRelationVoList.forEach(it -> materialTagRelationMapper.delById(it.getId(), it.getMerId()));
        }

        //添加素材和标签的关系
        if (materialDto.getTagIdList() != null && !materialDto.getTagIdList().isEmpty()) {
            for (Long tagId : materialDto.getTagIdList()) {
                MaterialTagRelation materialTagRelation = new MaterialTagRelation();
                materialTagRelation.setMerId(material.getMerId());
                materialTagRelation.setMaterialId(material.getId());
                materialTagRelation.setTagId(tagId);
                materialTagRelationMapper.add(materialTagRelation);
            }
        }
    }


    @Override
    public Object getMaterialLibraryList(MaterialQuery materialQuery) {

        if (materialQuery.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (materialQuery.getOperatorType() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "账号类型为空");
        }
        //如果查询人是子账号，必须有子账号ID
        if (materialQuery.getOperatorType() == 1 && materialQuery.getChildId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "子账号ID不存在");
        }

        if (materialQuery.getType() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "类型不能为空");
        }
        if (materialQuery.getType() == 1) {
            materialQuery.setChildId(null);
        }
        //主账号查看个人素材，子账号为主账号ID
        if (materialQuery.getType() == 2) {
            if (materialQuery.getOperatorType() == 0 && materialQuery.getChildId() == null) {
                materialQuery.setChildId(materialQuery.getMerId());
            }
        }

        //通过标签获取素材ID列表
        if (materialQuery.getTagIds() != null && !materialQuery.getTagIds().isEmpty()) {
            MaterialTagRelationQuery materialTagRelationQuery = new MaterialTagRelationQuery();
            materialTagRelationQuery.setMerId(materialQuery.getMerId());
            materialTagRelationQuery.setTagIds(materialQuery.getTagIds());
            List<MaterialTagRelationVo> materialTagRelationVoList = materialTagRelationMapper.getMaterialTagRelationList(materialTagRelationQuery);
            if (materialTagRelationVoList == null || materialTagRelationVoList.isEmpty()) {
                return new MyPageInfo<>(null);
            }
            List<Long> materialIds = materialTagRelationVoList.stream().map(MaterialTagRelationVo::getMaterialId).distinct().collect(Collectors.toList());
            materialQuery.setMaterialIds(materialIds);

        }

        String orderBy = OrderByUtil.getOrderBy(materialQuery.getOrderByField(), materialQuery.isAsc());
        PageHelper.startPage(materialQuery.getCurrent(), materialQuery.getSize(), orderBy);

        List<MaterialVo> materialVoList = materialMapper.getMaterialLibraryList(materialQuery);

        if (materialVoList != null && !materialVoList.isEmpty()) {

            for (MaterialVo materialVo : materialVoList) {
                try {
                    //设置消息数据列表
                    if (!StringUtils.isBlank(materialVo.getMsgDatas())) {
                        materialVo.setMsgDataList(JSONObject.parseArray(materialVo.getMsgDatas(), MsgData.class));
                    }

                    //获取标签名
                    MaterialTagRelationQuery materialTagRelationQuery = new MaterialTagRelationQuery();
                    materialTagRelationQuery.setMerId(materialQuery.getMerId());
                    materialTagRelationQuery.setMaterialId(materialVo.getId());

                    List<MaterialTagRelationVo> materialTagRelationVoList = materialTagRelationMapper.getMaterialTagRelationList(materialTagRelationQuery);

                    if (materialTagRelationVoList != null && !materialTagRelationVoList.isEmpty()) {

                        List<Long> TagIds = materialTagRelationVoList.stream().map(MaterialTagRelationVo::getTagId).distinct().collect(Collectors.toList());

                        MaterialLibraryTagQuery materialLibraryTagQuery = new MaterialLibraryTagQuery();
                        materialLibraryTagQuery.setMerId(materialQuery.getMerId());
                        materialLibraryTagQuery.setTagIds(TagIds);

                        List<MaterialLibraryTagVo> materialLibraryTagVoList = materialTagMapper.getMaterialLibraryTagList(materialLibraryTagQuery);

                        if (materialTagRelationVoList != null && !materialTagRelationVoList.isEmpty()) {

                            List<String> tagNameList = materialLibraryTagVoList.stream().map(MaterialLibraryTagVo::getName).distinct().collect(Collectors.toList());
                            materialVo.setTagNameList(tagNameList);

                        }


                    }


                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        return new MyPageInfo<>(materialVoList);
    }


    @Override
    public Object getMaterialLibraryDetail(MaterialDto materialDto) {
        if (materialDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (materialDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }

        Material material = materialMapper.getById(materialDto.getId(), materialDto.getMerId());

        if (material == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该素材不存在");
        }

        MaterialVo materialVo = new MaterialVo();
        BeanUtil.copyProperties(material, materialVo);

        //设置消息数据列表
        if (!StringUtils.isBlank(materialVo.getMsgDatas())) {
            materialVo.setMsgDataList(JSONObject.parseArray(materialVo.getMsgDatas(), MsgData.class));
        }

        //获取标签名
        MaterialTagRelationQuery materialTagRelationQuery = new MaterialTagRelationQuery();
        materialTagRelationQuery.setMerId(materialVo.getMerId());
        materialTagRelationQuery.setMaterialId(materialVo.getId());

        List<MaterialTagRelationVo> materialTagRelationVoList = materialTagRelationMapper.getMaterialTagRelationList(materialTagRelationQuery);

        if (materialTagRelationVoList != null && !materialTagRelationVoList.isEmpty()) {

            List<Long> TagIds = materialTagRelationVoList.stream().map(MaterialTagRelationVo::getTagId).distinct().collect(Collectors.toList());

            MaterialLibraryTagQuery materialLibraryTagQuery = new MaterialLibraryTagQuery();
            materialLibraryTagQuery.setMerId(materialVo.getMerId());
            materialLibraryTagQuery.setTagIds(TagIds);

            List<MaterialLibraryTagVo> materialLibraryTagVoList = materialTagMapper.getMaterialLibraryTagList(materialLibraryTagQuery);

            if (materialTagRelationVoList != null && !materialTagRelationVoList.isEmpty()) {

                List<String> tagNameList = materialLibraryTagVoList.stream().map(MaterialLibraryTagVo::getName).distinct().collect(Collectors.toList());
                materialVo.setTagNameList(tagNameList);

                List<Long> tagIds = materialLibraryTagVoList.stream().map(MaterialLibraryTagVo::getId).distinct().collect(Collectors.toList());
                materialVo.setTagIdList(tagIds);
            }
        }


        return materialVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delMaterialLibrary(BatchdelMaterialLibraryDto batchdelMaterialLibraryDto) {

        if (batchdelMaterialLibraryDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (batchdelMaterialLibraryDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }

        Material material = materialMapper.getById(batchdelMaterialLibraryDto.getId(), batchdelMaterialLibraryDto.getMerId());

        if (material == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该素材不存在");
        }

        //删除素材和标签的关系
        MaterialTagRelationQuery materialTagRelationQuery = new MaterialTagRelationQuery();
        materialTagRelationQuery.setMerId(material.getMerId());
        materialTagRelationQuery.setMaterialId(material.getId());
        List<MaterialTagRelationVo> materialTagRelationVoList = materialTagRelationMapper.getMaterialTagRelationList(materialTagRelationQuery);
        if (materialTagRelationVoList != null && !materialTagRelationVoList.isEmpty()) {
            materialTagRelationVoList.forEach(it -> materialTagRelationMapper.delById(it.getId(), it.getMerId()));
        }

        //删除素材
        materialMapper.delById(material.getId(), material.getMerId());
    }

    @Override
    public void updateImportant(UpdateImportantDto updateImportantDto) {

        if (updateImportantDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (updateImportantDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        if (updateImportantDto.getImportant() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAMETER_ERROR);
        }

        Material material = materialMapper.getById(updateImportantDto.getId(), updateImportantDto.getMerId());

        if (material == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该素材不存在");
        }

        material.setImportant(updateImportantDto.getImportant());
        materialMapper.update(material);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addMaterialConfig(MaterialConfigDto materialConfigDto) {

        if (materialConfigDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (materialConfigDto.getMobileCollectStatus() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "手机端采集是否启用为空");
        }
        if (materialConfigDto.getEnterpriseClean() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "企业素材是否自动清理为空");
        }
        if (materialConfigDto.getEnterpriseImportantClean() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "企业重要素材是否自动清理为空");
        }
        if (materialConfigDto.getPrivateClean() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "个人素材是否自动清理为空");
        }
        if (materialConfigDto.getPrivateImportantClean() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "个人素材是否自动清理为空");
        }

        if (materialConfigDto.getOperatorType() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "账号类型错误");
        }
        //子账号必须要有子账号id
        if (materialConfigDto.getOperatorType() == 1 && materialConfigDto.getChildId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "子账号ID不存在");
        }
        //主账号操作时保存的是主账号id
        if (materialConfigDto.getOperatorType() == 0) {
            materialConfigDto.setChildId(materialConfigDto.getMerId());
        }

        int time = DateUtil.getTime();

        MaterialConfig materialConfig = new MaterialConfig();
        BeanUtil.copyProperties(materialConfigDto, materialConfig);
        long id = IdWorker.getId();
        materialConfig.setId(id);
        materialConfig.setCreateTime(time);
        materialConfig.setUpdateTime(time);
        materialConfigMapper.insert(materialConfig);


        //添加素材库配置的群信息
        if (materialConfigDto.getMaterialConfigGroupDtoList() != null && !materialConfigDto.getMaterialConfigGroupDtoList().isEmpty()) {

            for (MaterialConfigGroupDto materialConfigGroupDto : materialConfigDto.getMaterialConfigGroupDtoList()) {

                MaterialConfigGroup materialConfigGroup = new MaterialConfigGroup();
                BeanUtil.copyProperties(materialConfigGroupDto, materialConfigGroup);
                materialConfigGroup.setConfigId(id);
                materialConfigGroupMapper.add(materialConfigGroup);

            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateMaterialConfig(MaterialConfigDto materialConfigDto) {
        if (materialConfigDto.getId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.ID_NULL);
        }
        if (materialConfigDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (materialConfigDto.getMobileCollectStatus() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "手机端采集是否启用为空");
        }
        if (materialConfigDto.getEnterpriseClean() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "企业素材是否自动清理为空");
        }
        if (materialConfigDto.getEnterpriseImportantClean() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "企业重要素材是否自动清理为空");
        }
        if (materialConfigDto.getPrivateClean() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "个人素材是否自动清理为空");
        }
        if (materialConfigDto.getPrivateImportantClean() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "个人素材是否自动清理为空");
        }

        if (materialConfigDto.getOperatorType() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "账号类型错误");
        }
        //子账号必须要有子账号id
        if (materialConfigDto.getOperatorType() == 1 && materialConfigDto.getChildId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "子账号ID不存在");
        }
        //主账号操作时保存的是主账号id
        if (materialConfigDto.getOperatorType() == 0) {
            materialConfigDto.setChildId(materialConfigDto.getMerId());
        }

        MaterialConfig materialConfig = materialConfigMapper.getById(materialConfigDto.getId(), materialConfigDto.getMerId());

        if (materialConfig == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该素材配置不存在");
        }

        BeanUtil.copyProperties(materialConfigDto, materialConfig);
        materialConfigMapper.update(materialConfig);

        //素材库配置的群信息
        MaterialConfigGroupQuery materialConfigGroupQuery = new MaterialConfigGroupQuery();
        materialConfigGroupQuery.setMerId(materialConfig.getMerId());
        materialConfigGroupQuery.setConfigId(materialConfig.getId());
        List<MaterialConfigGroupVo> materialConfigGroupVoList = materialConfigGroupMapper.getMaterialConfigGroupList(materialConfigGroupQuery);
        if (materialConfigGroupVoList != null && !materialConfigGroupVoList.isEmpty()) {
            materialConfigGroupVoList.forEach(it -> materialConfigGroupMapper.delById(it.getId(), it.getMerId()));
        }


        //添加素材库配置的群信息
        if (materialConfigDto.getMaterialConfigGroupDtoList() != null && !materialConfigDto.getMaterialConfigGroupDtoList().isEmpty()) {

            for (MaterialConfigGroupDto materialConfigGroupDto : materialConfigDto.getMaterialConfigGroupDtoList()) {

                MaterialConfigGroup materialConfigGroup = new MaterialConfigGroup();
                BeanUtil.copyProperties(materialConfigGroupDto, materialConfigGroup);
                materialConfigGroup.setConfigId(materialConfig.getId());
                materialConfigGroupMapper.add(materialConfigGroup);

            }
        }
    }


    @Override
    public Object getMaterialConfig(BaseDto baseDto) {
        if (baseDto.getMerId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.MERID_NULL);
        }
        if (baseDto.getOperatorType() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "账号类型错误");
        }
        //子账号必须要有子账号id
        if (baseDto.getOperatorType() == 1 && baseDto.getChildId() == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "子账号ID不存在");
        }
        //主账号操作时保存的是主账号id
        if (baseDto.getOperatorType() == 0) {
            baseDto.setChildId(baseDto.getMerId());
        }

        MaterialConfig materialConfig = materialConfigMapper.getByMerIdAndChildId(baseDto.getMerId(), baseDto.getChildId());

        if (materialConfig == null) {
            return null;
        }

        MaterialConfigVo materialConfigVo = new MaterialConfigVo();
        BeanUtil.copyProperties(materialConfig, materialConfigVo);


        //素材库配置的群信息
        MaterialConfigGroupQuery materialConfigGroupQuery = new MaterialConfigGroupQuery();
        materialConfigGroupQuery.setMerId(materialConfigVo.getMerId());
        materialConfigGroupQuery.setConfigId(materialConfigVo.getId());
        List<MaterialConfigGroupVo> materialConfigGroupVoList = materialConfigGroupMapper.getMaterialConfigGroupList(materialConfigGroupQuery);

        if (materialConfigGroupVoList != null && !materialConfigGroupVoList.isEmpty()) {

            for (MaterialConfigGroupVo materialConfigGroupVo : materialConfigGroupVoList) {
                try {
                    //获取机器人昵称 头像
                    WwDevice wwDevice = wwDeviceMapper.getById(materialConfigGroupVo.getDeviceUniqueId(), materialConfigGroupVo.getMerId());
                    materialConfigGroupVo.setDeviceName(wwDevice.getDeviceName());
                    materialConfigGroupVo.setDeviceHeadImageUrl(wwDevice.getHeadImgUrl());

                    //获取标签名列表
                    ObjectMapper objectMapper = new ObjectMapper();
                    List<Long> tagIds = objectMapper.readValue(materialConfigGroupVo.getTags(), new TypeReference<List<Long>>() {
                    });
                    if (tagIds != null && !tagIds.isEmpty()) {
                        MaterialLibraryTagQuery materialLibraryTagQuery = new MaterialLibraryTagQuery();
                        materialLibraryTagQuery.setMerId(materialConfigGroupVo.getMerId());
                        materialLibraryTagQuery.setTagIds(tagIds);
                        List<MaterialLibraryTagVo> materialLibraryTagVoList = materialTagMapper.getMaterialLibraryTagList(materialLibraryTagQuery);
                        if (materialLibraryTagVoList != null && !materialLibraryTagVoList.isEmpty()) {
                            List<String> tagNames = materialLibraryTagVoList.stream().map(MaterialLibraryTagVo::getName).distinct().collect(Collectors.toList());
                            materialConfigGroupVo.setTagNames(tagNames);
                        }
                    }


                    //获取群ID和群名称
                    WwGroup wwGroup = wwGroupMapper.getByGroupWxid(materialConfigGroupVo.getGroupWxid(), materialConfigGroupVo.getDeviceId(), materialConfigGroupVo.getMerId());
                    if (wwGroup != null) {
                        materialConfigGroupVo.setGroupId(wwGroup.getId());
                        materialConfigGroupVo.setGroupName(wwGroup.getGroupName());
                    }
                } catch (Exception e) {

                }
            }
            materialConfigVo.setMaterialConfigGroupVoList(materialConfigGroupVoList);
        }

        return materialConfigVo;
    }
}
